package cn.wolfcode.trip.base.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public abstract class DateUtil {

    public static String formatDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd");
        return format.format (date);
    }

    public static Date getFormatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
        String s = sdf.format (date);
        try {
            return sdf.parse (s);
        } catch (ParseException e) {
            e.printStackTrace ();
        }
        return null;
    }

    public static Date getEndDate(Date date) {
        if (date == null) {
            return null;
        }
        Calendar c = Calendar.getInstance ();
        c.setTime (date);
        c.set (Calendar.HOUR, 23);
        c.set (Calendar.MINUTE, 59);
        c.set (Calendar.SECOND, 59);
        return c.getTime ();
    }

    public static Date getPreviousDate(Date date) {
        return getFormatDate (computingTime (date, Calendar.DATE, -1));
    }

    public static Date getSevenDaysAgo(Date now) {
        return computingTime (now, Calendar.DAY_OF_MONTH, -7);
    }

    public static Date getAMonthAgo(Date now) {
        return computingTime (now, Calendar.MONTH, -1);
    }

    private static Date computingTime(Date now, int field, int amount) {
        if (now == null) {
            return null;
        }
        Calendar c = Calendar.getInstance ();
        c.setTime (now);
        c.add (field, amount);
        c.set (Calendar.HOUR_OF_DAY, 0);
        c.set (Calendar.MINUTE, 0);
        c.set (Calendar.SECOND, 0);
        return c.getTime ();
    }
}
